package cn.qyd.threadsignal;

import java.util.concurrent.Phaser;

/**
 * @author 邱运铎
 * Phaser 同步工具类 比 CyclicBarrier 工具类更加灵活强大
 * @date 2024-03-19 12:33
 */
public class PhaserDemo {
    static class Task implements Runnable{
        private final Phaser phaser;
        public Task(Phaser phaser) {
            this.phaser = phaser;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + " 已完成第一个任务。。。");
                phaser.arriveAndAwaitAdvance();
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + " 已完成第二个任务。。。");
                phaser.arriveAndAwaitAdvance();
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + " 已完成第三个任务。。。");
                phaser.arriveAndAwaitAdvance();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Phaser phaser = new Phaser(3);

        new Thread(new Task(phaser)).start();
        new Thread(new Task(phaser)).start();
        //arriveAndDeregister方法使当前phaser需要的线程数量减一
        phaser.arriveAndDeregister();
//        new Thread(new Task(phaser)).start();
    }
}
